import Router from 'koa-router';
import Poi from '../dbs/models/poi'
import axios from './util/axios'
import Keyword from '../dbs/models/keyword'


let router = new Router({prefix: '/search'})


router.get('/top', async (ctx) => {
  try {
    let top = await Poi.find({
      'name': new RegExp(ctx.query.input),
    })
    ctx.body = {
      status: true,
      top: top.map(item => {
        return {
          name: item.name,
          type: item.type
        }
      }),
      type: top.length ? top[0].type : ''
    }
  } catch (e) {
    ctx.body = {
      code: false,
      top: []
    }
  }

})
router.get('/hotPlace', async (ctx) => {
  let city =  ctx.query.city
  try {
    let result = await Poi.find({
      city,
    }).limit(10)
    ctx.body = {
      status: true,
      result: result.map(item => {
        return {
          name: item.name,
          type: item.type
        }
      })
    }
  } catch (e) {
    ctx.body = {
      status: false,
      result: []
    }
  }

})
router.get('/resultsByKeywords', async (ctx) => {
  const {city, keyword} = ctx.query;
  // try {
  //   let result = await Keyword.find()
  //   ctx.body = {
  //     status: true,
  //     data: result
  //   }
  // } catch (e) {
  //   ctx.body = {
  //     status: false,
  //     result: []
  //   }
  // }
  let res = await axios.get('http://cp-tools.cn/search/resultsByKeywords', {params: {city, keyword,}})
    ctx.body = {
    status: true,
    count: res.count,
    pois: res.pois
  }

})


router.get('/products', async (ctx) => {
  let keyword = ctx.query.keyword || '旅游'
  let city = ctx.query.city || '北京'
  let {product, more} = await axios.get('http://cp-tools.cn/search/products', {params: {keyword, city,}})
  ctx.body = {
    status: true,
    product,
    more: ctx.isAuthenticated() ? more: [],
    login: ctx.isAuthenticated()
  }

})

export default router
